import { StrType } from "@/service/general/enumType";
import { UtilHelpers } from "@/service/general/utils/utilHelpers";
import { useEffect, useState } from "react";

interface viewData {
    id: string,
    name: string,
    value: string,
    type: string
}

const PlayBook = ({data, setProcessParam, callback}: {data: string, setProcessParam: (param: string) => void, callback?: (param: any) => void}) => {
    const [isLoad, setIsLoad] = useState(true);
    const [dataType, setDataType] = useState<StrType>(StrType.OTHER);
    const [viewDatas, setViewDatas] = useState<viewData[]>([]);
    useEffect(() => {
        Initialize();
    });

    const Initialize = () => {
        if (isLoad) {
            setIsLoad(false);
            if (data) {
                ParsingData();
            }
            
        }
    }

    const ParsingData = () => {
        const type = UtilHelpers.getStrType(data);
        setDataType(type);
        if (type === StrType.ARRAY) {
            const objs:[] = JSON.parse(data);
            const itemType = objs.filter(item => UtilHelpers.getStrType(item) === StrType.OBJECT).length || 0;
            if (itemType > 0) {
                setViewDatas((val) => {
                    return [{
                        id: "array_view_" + 0 + "-" + 0,
                        name: "",
                        value: val.join('\n'),
                        type: "text"
                    }];
                });
            } else {
                objs.map((item, index) => {
                    Object.keys(item).map((key, keyIndex) => {
                        const obj: viewData = {
                            id: "array_view_" + index + "-" + keyIndex,
                            name: key,
                            value: JSON.stringify(item[key], null, 2),
                            type: Array.isArray(item[key]) ? 'array' : typeof item[key]
                        }
                    });
                });
            }
        } else if (type === StrType.OBJECT) {
            setViewDatas([]);
            const obj = JSON.parse(data);
            Object.keys(obj).map((key, index) => {
                const item: viewData = {
                    id: "obj_view_" + index,
                    name: key,
                    value: JSON.stringify(obj[key], null, 2),
                    type: Array.isArray(obj[key]) ? 'array' : typeof obj[key]
                }
                setViewDatas((datas) => [...datas, item]);
            });
        } else {
            setViewDatas((val) => {
                    return [{
                        id: "other_view_" + 0,
                        name: "",
                        value: data,
                        type: "text"
                    }];
                });
        }
    }

    const onChangeArray = (id: string, value: string) => {
        setViewDatas((datas) => {
            const newArray = [...datas.map((item) => {
                if (item.id === id) {
                    const newItem = {
                        ...item,
                        value: value
                    }
                    return newItem;
                }
                return item;
            })];
            if (dataType === StrType.ARRAY) {
                const jsonObjs: {[key: string]: any} = {};
                newArray.forEach(item => {
                    const index = item.id.substring(0, item.id.indexOf('-'));
                    if (!jsonObjs[index]) jsonObjs[index] = {};
                    jsonObjs[index][item.name] = item.value;
                });
                const jsonStr =  JSON.stringify(jsonObjs);
                setProcessParam(jsonStr);
            } else if (dataType === StrType.OBJECT) {
                const jsonObjs: {[key: string]: any} = {};
                newArray.forEach(item => {
                    jsonObjs[item.name] = item.value;
                });
                const jsonStr =  JSON.stringify(jsonObjs);
                setProcessParam(jsonStr);
            } else if (dataType === StrType.INVALID) {
                const jsonStr =  newArray[0].value;
                setProcessParam(jsonStr);
            } else {

            }
            
            return [...newArray];
        })
    }
    

    return viewDatas.map((item, index) => (<>
        <div key={`process_${index}_${item.id}`} className="w-full h-11 flex flex-row items-center justify-start gap-2">
            <div className="h-full text-center flex flex-row items-center justify-center">{item.name}</div>
            <div className="flex-1 h-11 flex flex-row items-center justify-center rounded-lg border p-2 has-[input:focus-within]:border-blue-500/60">
                <input 
                value={item.value} 
                className="w-full h-full border-none outline-none"
                onChange={(e) => {onChangeArray(item.id, e.target.value)}} />
            </div>
        </div>
    </>));
}

export {
    PlayBook
}